package flc.ast.dialog;

import android.app.Activity;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ToastUtils;
import com.stark.mindmap.lib.R;
import com.stark.mindmap.lib.core.layout.MindLayoutType;
import com.stark.mindmap.lib.core.model.DefNodeData;
import com.stark.mindmap.lib.core.model.LayoutTreeModel;
import com.stark.mindmap.lib.core.util.MindUtil;

import flc.ast.databinding.DialogMdmSaveBinding;
import stark.common.basic.base.BaseEventDialog;

/**
 * Author：daizhongbin on 2023/8/15
 * Email：1027154338@qq.com
 * Desc:
 */
public class MyMindSaveDialog extends BaseEventDialog<DialogMdmSaveBinding> {

    private LayoutTreeModel<DefNodeData> layoutTreeModel;
    private MindLayoutType layoutType;

    public void setLayoutTreeModel(LayoutTreeModel<DefNodeData> treeModel) {
        this.layoutTreeModel = treeModel;
    }

    public void setLayoutType(MindLayoutType layoutType) {
        this.layoutType = layoutType;
    }

    public MyMindSaveDialog(@NonNull Activity activity) {
        super(activity);
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.dialog_mdm_save;
    }

    @Override
    protected void initContentView(View view) {
        mContentDataBinding.ivDialogSaveCancel.setOnClickListener(v -> {
            dismiss();
        });
        mContentDataBinding.ivDialogSaveConfirm.setOnClickListener(v -> {
            handleSave();
        });
    }

    private void handleSave() {
        String fileName = mContentDataBinding.etDialogSaveName.getText().toString().trim();
        if (TextUtils.isEmpty(fileName)) {
            ToastUtils.showShort(com.stark.common.res.R.string.please_input_value);
            mContentDataBinding.etDialogSaveName.requestFocus();
            return;
        }
        if (MindUtil.isFileNameExist(fileName)) {
            ToastUtils.showShort(com.stark.common.res.R.string.file_name_exist);
            mContentDataBinding.etDialogSaveName.requestFocus();
            return;
        }
        boolean ret = MindUtil.saveTreeModel2File(fileName, layoutTreeModel);
        if (listener != null && ret) {
            listener.onSaveSuccess();
        }
        ToastUtils.showShort(ret ? com.stark.common.res.R.string.save_success : com.stark.common.res.R.string.save_failure);
        dismiss();
    }

    private IListener listener;

    public void setListener(IListener listener) {
        this.listener = listener;
    }

    public interface IListener {

        void onSaveSuccess();

    }
}
